import './styles/reset.css';
import './styles/themes.css';
import styles from './App.module.css';
import { useRef, useState, useEffect } from 'react';
import { Toolbar, Editor, Terminal } from './components';
import { FileBar } from './components/editor';
import ExportDialogSimple from './components/dialogs/ExportDialogSimple';
import { MessageContainer } from './components/message';
import Sidebar from './components/sidebar';
import { useMessage } from './hooks/useMessage';
import { usePythonPlayer } from './hooks/usePythonPlayer';
import { 
  useAppStore, 
  useProjectStore,
  useEditorStore,
  useTerminalVisibility,
  useSidebarActions,
} from './stores';
import globalEventManager from './utils/eventManager';
import projectManager from './utils/projectManager';
import { globalPlayer } from 'python-player';
import { FaChevronLeft, FaChevronRight, FaBars } from 'react-icons/fa6';

const App = () => {
  const { isDarkTheme } = useAppStore();
  const { getCurrentFileInfo, getProjectInfo } = useProjectStore();
  const { saveNow } = useEditorStore();
  const { 
    isVisible: isTerminalVisible, 
    toggleVisibility: toggleTerminal 
  } = useTerminalVisibility();
  
  const { 
    isOpen: isSidebarOpen, 
    toggleSidebar, 
    isMobileDevice 
  } = useSidebarActions();
  
  const { handleEditorReady, editorRef } = usePythonPlayer();
  const outputContentRef = useRef(null);
  
  const [exportDialog, setExportDialog] = useState({
    isOpen: false,
    code: '',
    fileName: 'main.py'
  });

  // 消息提示
  const { messages, removeMessage, clearMessages, success, error } = useMessage();


  // 缓存当前文件信息，避免重复调用
  const currentFileInfo = getCurrentFileInfo();
  const projectInfo = getProjectInfo();
  
  // 获取当前文件的最后保存时间
  const currentProject = projectInfo?.currentProject;
  const currentFileId = currentFileInfo?.id;
  const lastSaved = currentFileId ? currentProject?.getFileLastSaved(currentFileId) : null;

  useEffect(() => {
    globalPlayer.setEventManager(globalEventManager);
  }, []);

  // 键盘快捷键处理
  useEffect(() => {
    const handleKeyDown = async (event) => {
      // Ctrl+Shift+S 保存作品
      if (event.ctrlKey && event.shiftKey && event.key === 'S') {
        event.preventDefault();
        
        try {
          console.log('快捷键触发保存作品');
          const result = await projectManager.saveProject();
          if (result.success) {
            console.log('快捷键保存作品成功:', result.data);
            success('作品保存成功');
          } else {
            console.warn('快捷键保存作品失败:', result.error);
            error(result.error || '保存失败');
          }
        } catch (err) {
          console.error('快捷键保存作品出错:', err);
          error(`保存出错: ${err.message}`);
        }
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    
    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, []);

  const handleTerminalReady = (terminalRef) => {
    outputContentRef.current = terminalRef.current;
  };

  // 显示导出对话框
  const handleShowExportDialog = () => {
    clearMessages();
    // 重置对话框状态
    setExportDialog({ isOpen: true, code: '', fileName: 'main.py' });
  };

  const handleCloseExportDialog = () => {
    setExportDialog(prev => ({ ...prev, isOpen: false }));
  };

  // 检查是否为移动端
  const isMobile = isMobileDevice();

  return (
    <div 
      className={styles.content}
      data-theme={isDarkTheme ? 'dark' : 'light'}
    >
      {/* 移动端侧边栏切换按钮 */}
      {isMobile && (
        <button
          className={styles.mobileSidebarToggle}
          onClick={toggleSidebar}
          title={isSidebarOpen ? '关闭文件浏览器' : '打开文件浏览器'}
        >
          <FaBars />
        </button>
      )}
      
      <Toolbar onShowExportDialog={handleShowExportDialog} />
      <FileBar 
        fileName={currentFileInfo?.name || '未命名文件'} 
        filePath={currentFileInfo ? `/${currentFileInfo.name}` : ''}
        lastSaved={lastSaved}
      />
      <div className={styles.appBody}>
        <Sidebar />
        <div className={styles.mainContent}>
          <Editor
            onEditorReady={handleEditorReady}
            isDarkTheme={isDarkTheme}
          />
          
          <button
            className={styles.terminalToggle}
            onClick={toggleTerminal}
            title={isTerminalVisible ? '隐藏控制台' : '显示控制台'}
          >
            {isTerminalVisible ? <FaChevronLeft /> : <FaChevronRight />}
          </button>
          
          <Terminal
            onTerminalReady={handleTerminalReady}
            isVisible={isTerminalVisible}
          />
        </div>
      </div>
      
      {/* 导出对话框 */}
      <ExportDialogSimple
        isOpen={exportDialog.isOpen}
        onClose={handleCloseExportDialog}
      />

      {/* 消息提示 */}
      <MessageContainer 
        messages={messages} 
        onRemoveMessage={removeMessage} 
      />
    </div>
  );
};

export default App;